package logic

import (
	"common/global"
	"common/model"
	"context"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"time"
	"user_server/proto"
)

var prizes = []struct {
	name string
	prob int // 概率权重
}{
	{"谢谢参与", 50},
	{"补签卡一张", 30},
	{"补签卡两张", 15},
	{"iPhone", 5},
}

func (s *UserServer) LuckyDraw(ctx context.Context, req *user.LuckyDrawRequest) (*user.LuckyDrawResponse, error) {
	userId := req.UserId
	today := time.Now().Format("2006-01-02")

	// 检查当日是否已抽奖
	redisKey := fmt.Sprintf("user:luckydraw:%d:%s", userId, today)
	result, err := global.Client.SetNX(ctx, redisKey, 1, 24*time.Hour).Result()
	if !result || err != nil {
		return &user.LuckyDrawResponse{
			Success: false,
			Message: "今日已抽过奖",
		}, nil
	}

	tx := global.Db.Begin()
	var o model.User
	if err := tx.Where("id = ?", userId).First(&o).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("用户不存在")
	}

	// 随机抽奖
	rand.Seed(time.Now().UnixNano())
	totalProb := 100
	pick := rand.Intn(totalProb)
	var prize string
	var cards int

	currentProb := 0
	for _, p := range prizes {
		currentProb += p.prob
		if pick < currentProb {
			prize = p.name
			switch p.name {
			case "补签卡一张":
				cards = 1
			case "补签卡两张":
				cards = 2
			}
			break
		}
	}

	// 更新补签卡数量
	if cards > 0 {
		if err := tx.Model(&o).Update("retroactive_cards",
			gorm.Expr("retroactive_cards + ?", cards)).Error; err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("奖品发放失败")
		}
	}

	// 创建抽奖记录
	record := model.LuckyDrawRecord{
		UserID:    userId,
		PrizeName: prize,
	}
	if err := tx.Create(&record).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("记录创建失败")
	}

	if err := tx.Commit().Error; err != nil {
		return nil, fmt.Errorf("事务提交失败")
	}

	return &user.LuckyDrawResponse{
		Success: true,
		Prize:   prize,
		Message: "抽奖成功",
	}, nil
}
